#include "Material.hpp"
#include "objLoader.h"
#include "tgaimage.h"

Material::Material(const obj_material * material)
  : m_ambient(material->amb[0],
              material->amb[1],
              material->amb[2],1.0f),
    m_diffuse(material->diff[0],
              material->diff[1],
              material->diff[2],1.0f),
    m_specular(material->spec[0],
               material->spec[1],
               material->spec[2],1.0f),
    m_shininess(material->shiny),
    m_filename(material->texture_filename)
{
  m_hasTexture = (m_filename[0] != '\0'); // if empty filename
  
  if (m_hasTexture) {
    glGenTextures(1, &m_tboHandle);
    glBindTexture(GL_TEXTURE_2D, m_tboHandle);
    
    #warning "Better image support required"
    TgaImage img(m_filename);
    
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 img.dataType,
                 img.imgWidth,
                 img.imgHeight,
                 0,
                 img.format,
                 GL_UNSIGNED_BYTE,
                 img.imgData);

    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  }
}

Material::Material(const char * filename)
  : m_ambient(1.0f,1.0f,1.0f,1.0f),
    m_diffuse(1.0f,1.0f,1.0f,1.0f),
    m_specular(1.0f,1.0f,1.0f,1.0f),
    m_shininess(1.0f),
    m_filename(filename)
{
  m_hasTexture = (m_filename[0] != '\0'); // if empty filename
  
  if (m_hasTexture) {
    glGenTextures(1, &m_tboHandle);
    glBindTexture(GL_TEXTURE_2D, m_tboHandle);
    
    #warning "Better image support required"
    TgaImage img(m_filename);
    
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 img.dataType,
                 img.imgWidth,
                 img.imgHeight,
                 0,
                 img.format,
                 GL_UNSIGNED_BYTE,
                 img.imgData);

    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  }
}